package com.zrc.japktool.apk.lib2cppTools.tools;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.zrc.japktool.util.TextUtils;
public class FileHelper {

    public static String read(String path) throws Exception {
        FileInputStream fileInputStream = new FileInputStream(path);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream), 10485760);
        String line = null;
        String ret = "";

        for(int x = 0; (line = bufferedReader.readLine()) != null; ret = ret + "\r\n") {
            if (x % 10000 == 0) {
                System.out.println(line);
            }

            ++x;
            ret = ret + line;
        }

        bufferedReader.close();
        fileInputStream.close();
        return ret;
    }

    public static int readByte(String path, byte[] buffer) throws Exception {
        FileInputStream fileInputStream = new FileInputStream(path);
        BufferedInputStream in = new BufferedInputStream(fileInputStream);
        int ret;
        int n;
        for(ret = -1; (n = in.read(buffer, 0, buffer.length)) != -1; ret = n) {
        }
        fileInputStream.close();
        in.close();
        return ret;
    }

    public static void replaceString(String path, String keyString, String newString) throws Exception {
        byte[] buffer = new byte[134217728];
        readByte(path, buffer);
        String content = new String(buffer, "ISO-8859-1");
        int beginIndex = content.indexOf(keyString);
        byte leftkeyByte = (byte)keyString.charAt(keyString.length() - 1);
        byte rightKeyByte = 125;
        if (leftkeyByte == 34) {
            rightKeyByte = leftkeyByte;
        }

        if (beginIndex != -1) {
            int left = 0;
            int right = 0;
            if (leftkeyByte == 34) {
                left = 2;
            }

            int endIndex;
            for(endIndex = beginIndex; endIndex < 134217728; ++endIndex) {
                if (buffer[endIndex] == leftkeyByte) {
                    if (leftkeyByte == rightKeyByte) {
                        ++right;
                    } else {
                        ++left;
                    }
                } else if (buffer[endIndex] == rightKeyByte) {
                    ++right;
                }

                if (left == right && left > 0) {
                    break;
                }
            }

            String oldString = content.substring(beginIndex + keyString.length(), endIndex);
            if (checkCountChinese(newString)) {
                replaceString(path, oldString.getBytes("ISO8859-1"), newString.getBytes("utf-8"));
            } else {
                replaceString(path, oldString.getBytes("ISO8859-1"), newString.getBytes("ISO8859-1"));
            }

        }
    }

    public static boolean checkCountChinese(String countname) {
        Pattern p = Pattern.compile("[一-龥]");
        Matcher m = p.matcher(countname);
        return m.find();
    }

    public static boolean replaceString(String path, byte[] oldString, byte[] newString) throws Exception {
        byte[] oldBytes = new byte[134217728];
        byte[] newBytes = new byte[134217728];
        int n = readByte(path, oldBytes);
        int x = oldString.length - newString.length;
        boolean ret = false;

        for(int i = 0; i < oldBytes.length; ++i) {
            int m = 0;

            for(int j = 0; j < oldString.length; ++j) {
                if (i + j < 134217728 && oldBytes[i + j] == oldString[j]) {
                    ++m;
                }
            }

            if (m == oldString.length) {
                System.arraycopy(oldBytes, 0, newBytes, 0, i);
                System.arraycopy(newString, 0, newBytes, i, newString.length);
                System.arraycopy(oldBytes, i + m, newBytes, i + newString.length, n - i - m);
                ret = true;
                break;
            }
        }

        if (ret) {
            writeByte(path, newBytes, n - x);
        }

        return ret;
    }

    public static void insertString(String path, int pos, byte[] newString) throws Exception {
        byte[] oldBytes = new byte[134217728];
        byte[] newBytes = new byte[134217728];
        int n = readByte(path, oldBytes);
        System.arraycopy(oldBytes, 0, newBytes, 0, pos);
        System.arraycopy(newString, 0, newBytes, pos, newString.length);
        System.arraycopy(oldBytes, pos, newBytes, pos + newString.length, n - pos);
        writeByte(path, newBytes, n + newString.length);
    }

    public static void write(String path, String content) throws Exception {
        File file = new File(path);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(content.getBytes());
        fileOutputStream.close();
    }

    public static void writeByte(String path, byte[] buffer, int n) throws Exception {
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(path));
        out.write(buffer, 0, n);
        out.flush();
        out.close();
    }

    public static boolean isFileExist(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return false;
        } else {
            File file = new File(filePath);
            return file.exists() && file.isFile();
        }
    }

    public static String folderMethod(String path, String name) {
        int fileNum = 0;
        int folderNum = 0;
        File file = new File(path);
        LinkedList<File> list = new LinkedList();
        if (file.exists()) {
            if (null == file.listFiles()) {
                return null;
            }

            list.addAll(Arrays.asList(file.listFiles()));

            label38:
            while(true) {
                File[] files;
                do {
                    if (list.isEmpty()) {
                        break label38;
                    }

                    files = ((File)list.removeFirst()).listFiles();
                } while(null == files);

                File[] var7 = files;
                int var8 = files.length;

                for(int var9 = 0; var9 < var8; ++var9) {
                    File f = var7[var9];
                    if (f.isDirectory()) {
                        list.add(f);
                        ++folderNum;
                    } else {
                        ++fileNum;
                        String filePath = f.getAbsolutePath();
                        String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1, filePath.length());
                        if (fileName.equals(name)) {
                            return filePath;
                        }
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }

        System.out.println("文件夹数量:" + folderNum + ",文件数量:" + fileNum);
        return null;
    }

    public static LinkedList<File> folderMethod(String path) {
        int fileNum = 0;
        int folderNum = 0;
        File file = new File(path);
        LinkedList<File> list = new LinkedList();
        if (file.exists()) {
            if (null == file.listFiles()) {
                return null;
            } else {
                list.addAll(Arrays.asList(file.listFiles()));
                return list;
            }
        } else {
            System.out.println("文件不存在!");
            System.out.println("文件夹数量:" + folderNum + ",文件数量:" + fileNum);
            return list;
        }
    }

    public static LinkedList<File> folderMethod1(String path) {
        File file = new File(path);
        LinkedList<File> list = new LinkedList();
        LinkedList<File> retlist = new LinkedList();
        if (file.exists()) {
            if (null == file.listFiles()) {
                return retlist;
            } else {
                list.addAll(Arrays.asList(file.listFiles()));

                while(true) {
                    File[] files;
                    do {
                        if (list.isEmpty()) {
                            return retlist;
                        }

                        files = ((File)list.removeFirst()).listFiles();
                    } while(null == files);

                    File[] var5 = files;
                    int var6 = files.length;

                    for(int var7 = 0; var7 < var6; ++var7) {
                        File f = var5[var7];
                        if (f.isDirectory()) {
                            list.add(f);
                        } else {
                            retlist.add(f);
                        }
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
            return retlist;
        }
    }

    public static void copyFile(File source, File dest) throws IOException {
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;

        try {
            inputChannel = (new FileInputStream(source)).getChannel();
            outputChannel = (new FileOutputStream(dest)).getChannel();
            outputChannel.transferFrom(inputChannel, 0L, inputChannel.size());
        } finally {
            inputChannel.close();
            outputChannel.close();
        }

    }

    public static boolean deleteDirectory(String sPath) {
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }

        File dirFile = new File(sPath);
        if (dirFile.exists() && dirFile.isDirectory()) {
            boolean flag = true;
            File[] files = dirFile.listFiles();

            for(int i = 0; i < files.length; ++i) {
                if (files[i].isFile()) {
                    flag = deleteFile(files[i].getAbsolutePath());
                    if (!flag) {
                        break;
                    }
                } else {
                    flag = deleteDirectory(files[i].getAbsolutePath());
                    if (!flag) {
                        break;
                    }
                }
            }

            if (!flag) {
                return false;
            } else {
                return dirFile.delete();
            }
        } else {
            return false;
        }
    }

    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }

        return flag;
    }

    public static void deleteLine(String path, String keyString) throws Exception {
        byte[] buffer = new byte[134217728];
        readByte(path, buffer);
        String content = new String(buffer, "ISO-8859-1");
        int index = content.indexOf(keyString);
        if (index != -1) {
            String oldString = "";
            int beginIndex;
            int endIndex;
            if (content.indexOf(new String(new byte[]{13, 10})) == -1) {
                for(beginIndex = index; beginIndex > 0 && buffer[beginIndex] != 10; --beginIndex) {
                }

                for(endIndex = index; endIndex < 134217728 && buffer[endIndex] != 10; ++endIndex) {
                }

                oldString = content.substring(beginIndex + 1, endIndex);
            } else {
                for(beginIndex = index; beginIndex > 0 && (buffer[beginIndex] != 13 || buffer[beginIndex + 1] != 10); --beginIndex) {
                }

                for(endIndex = index; endIndex < 134217728 && (buffer[endIndex] != 13 || buffer[endIndex + 1] != 10); ++endIndex) {
                }

                oldString = content.substring(beginIndex + 2, endIndex);
            }

            if (!TextUtils.isEmpty(oldString)) {
                String deleteString = "//" + oldString;
                replaceString(path, oldString.getBytes("ISO8859-1"), deleteString.getBytes("ISO8859-1"));
            }
        }
    }

    public static void createNewFile(String fileName) throws IOException {
        File f = new File(fileName);
        f.createNewFile();
    }

    public static void mkdirs(String path) throws IOException {
        File f = new File(path);
        f.mkdirs();
    }

    public static void dirCopy(String srcPath, String destPath) {
        File src = new File(srcPath);
        if (!(new File(destPath)).exists()) {
            (new File(destPath)).mkdirs();
        }

        File[] var3 = src.listFiles();
        int var4 = var3.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            File s = var3[var5];
            if (s.isFile()) {
                fileCopy(s.getPath(), destPath + File.separator + s.getName());
            } else {
                dirCopy(s.getPath(), destPath + File.separator + s.getName());
            }
        }

    }

    public static void fileCopy(String srcPath, String destPath) {
        File src = new File(srcPath);
        File dest = new File(destPath);

        try {
            InputStream is = new BufferedInputStream(new FileInputStream(src));
            Throwable var5 = null;

            try {
                OutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
                Throwable var7 = null;

                try {
                    byte[] flush = new byte[1024];
                    boolean var9 = true;

                    int len;
                    while((len = is.read(flush)) != -1) {
                        out.write(flush, 0, len);
                    }

                    out.flush();
                } catch (Throwable var35) {
                    var7 = var35;
                    throw var35;
                } finally {
                    if (out != null) {
                        if (var7 != null) {
                            try {
                                out.close();
                            } catch (Throwable var34) {
                                var7.addSuppressed(var34);
                            }
                        } else {
                            out.close();
                        }
                    }

                }
            } catch (Throwable var37) {
                var5 = var37;
                throw var37;
            } finally {
                if (is != null) {
                    if (var5 != null) {
                        try {
                            is.close();
                        } catch (Throwable var33) {
                            var5.addSuppressed(var33);
                        }
                    } else {
                        is.close();
                    }
                }

            }
        } catch (FileNotFoundException var39) {
            var39.printStackTrace();
        } catch (IOException var40) {
            var40.printStackTrace();
        }

    }

    public static long getLength(String filePath) {
        File file = new File(filePath);
        return file.length();
    }

    public static String readLargeFile(String path) throws Exception {
        String ret = "";
        FileInputStream fileInputStream = new FileInputStream(path);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
        int maxSize = 134217728;
        char[] array = new char[maxSize];
        int off = 0;

        int size;
        do {
            size = bufferedReader.read(array, off, maxSize);
            off += maxSize;
            ret = ret + new String(array);
        } while(size == maxSize);

        bufferedReader.close();
        fileInputStream.close();
        return ret;
    }

    public static void AppendTextToFile(String filename, String textToAppend) {
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(filename, true));
            Throwable var3 = null;

            try {
                writer.write(textToAppend);
            } catch (Throwable var13) {
                var3 = var13;
                throw var13;
            } finally {
                if (writer != null) {
                    if (var3 != null) {
                        try {
                            writer.close();
                        } catch (Throwable var12) {
                            var3.addSuppressed(var12);
                        }
                    } else {
                        writer.close();
                    }
                }

            }
        } catch (IOException var15) {
            System.err.println("Error writing to file: " + var15.getMessage());
        }

    }

    public static void EraserBadChar(String filePath) {
        try {
            List<String> cleanedLines = (List)Files.lines(Paths.get(filePath), StandardCharsets.UTF_8).map((line) -> {
                return line.replaceAll("\\P{Print}", "");
            }).collect(Collectors.toList());
            Files.write(Paths.get(filePath), cleanedLines, StandardCharsets.UTF_8);
            System.out.println("文件清理完成。");
        } catch (IOException var2) {
            System.out.println("处理文件时发生错误：" + var2.getMessage());
        }

    }
}
